sap.ui.define([
	"sap/ui/core/mvc/Controller",
	"sap/ui/model/json/JSONModel",
	"firorworkshop185/model/formatter",
], function (
	Controller,
	JSONModel,
	formatter
) {
	"use strict";

	return Controller.extend("firorworkshop185.controller.Detail", {
		formatter: formatter,
		onInit: function () {
			const oRouter = this.getOwnerComponent().getRouter();
			oRouter.getRoute("detail").attachPatternMatched(this._onObjectMatched, this);
			this.orderInfo = null;		//ENTITY001Set
			// this.productInfo = null;	//ENTITY002Set
			// this.customerInfo = null;	//ENTITY003Set
			// this.repPersonInfo = null;	//ENTITY004Set
			// this.orderStatusInfo = null;//ENTITY005Set
		},

		async filterData(orderItem) {
			this.orderInfo = orderItem;

			let productItem = null;
			let customerItem = null;
			let repPersonItem = null;
			let orderStatusItemList = null;

			let productItemPromise = this.getInfoItem("/ENTITY002Set(productID='" + orderItem.productID + "',languageKey='EN')");
			let customerItemPromise = orderItem.customerNo && orderItem.customerNo != "" ? this.getInfoItem("/ENTITY003Set(customerNo='" + orderItem.customerNo + "',languageKey='EN')") : null;
			let repPersonPromise = orderItem.repPersonNo && orderItem.repPersonNo != "" ? this.getInfoItem("/ENTITY004Set(repPersonNo='" + orderItem.repPersonNo + "',languageKey='EN')") : null;
			let orderStatusItemListPromise = this.getInfoItem("/ENTITY005Set?$filter=orderNo eq '" + orderItem.orderNo + "'");

			[productItem, customerItem, repPersonItem, orderStatusItemList] = await Promise.all([productItemPromise, customerItemPromise, repPersonPromise, orderStatusItemListPromise]);

			orderStatusItemList = orderStatusItemList.results.filter(element => element.orderNo == orderItem.orderNo);


			var oModel = this.getView().getModel('info');

			const obj = {
				orderItem: orderItem,
				productItem: productItem,
				customerItem: customerItem,
				repPersonItem: repPersonItem,
				orderStatusItemList: orderStatusItemList,
				getInfoCompleted: true
			};
			oModel.setData({
				...oModel.oData,
				orderDetail: obj
			});

			this.initMaintenanceHistory(orderStatusItemList);
		},

		initMaintenanceHistory(sourceList) {
			var oTable = this.getView().byId("orderDetailTable");
			console.log(sourceList);
			var oModel = new sap.ui.model.json.JSONModel({
				items: sourceList
			}, "MaintenanceHistoryList");
			oTable.setModel(oModel);
			let list = ["orderNo", "itemNo", "status", "changeDate", "changeTime"]
			let cell = [];
			list.forEach(element => {
				if (element == "changeDate") {
					cell.push(new sap.m.Text({
						text: {
							path: 'changeDate',
							formatter: formatter.returnDate
						}
					}));
				}
				else if (element == "changeTime") {
					cell.push(new sap.m.Text({
						text: {
							path: 'changeDate',
							formatter: formatter.returnTime
						}
					}));
				}
				else {
					cell.push(new sap.m.Text({
						text: "{" + element + "}"
					}));
				}
			});
			oTable.setModel(oModel);
			oTable.bindItems("/items", new sap.m.ColumnListItem({
				cells: cell
			}));
		},

		async refreshTable() {
			var oModel = this.getView().getModel('info');
			const obj = {
				orderItem: oModel.oData.orderDetail.orderItem,
				productItem: oModel.oData.orderDetail.productItem,
				customerItem: oModel.oData.orderDetail.customerItem,
				repPersonItem: oModel.oData.orderDetail.repPersonItem,
				orderStatusItemList: null,
				getInfoCompleted: false
			};
			oModel.setData({
				...oModel.oData,
				orderDetail: obj
			});

			let orderStatusItemListPromise = this.getInfoItem("/ENTITY005Set?$filter=orderNo eq '" + this.orderInfo.orderNo + "'");
			let orderStatusItemList = await Promise.all([orderStatusItemListPromise]);
			orderStatusItemList = orderStatusItemList[0].results.filter(element => element.orderNo == this.orderInfo.orderNo);
			obj.orderStatusItemList = orderStatusItemList;
			obj.getInfoCompleted = true;
			oModel.setData({
				...oModel.oData,
				orderDetail: obj
			});
			this.initMaintenanceHistory(orderStatusItemList);
		},

		_onObjectMatched(oEvent) {
			var oArgs = oEvent.getParameter("arguments");
			// let par = {
			// 	pars: JSON.stringify(oArgs)
			// }
			// const oModel = new JSONModel(par);
			console.log(oArgs.id);
			this.getOrderItem(oArgs.id);
		},

		getOrderItem(id) {
			var oModel = this.getView().getModel('info');
			const obj = {
				orderItem: null,
				productItem: null,
				customerItem: null,
				repPersonItem: null,
				orderStatusItemList: null,
				getInfoCompleted: false
			};
			oModel.setData({
				...oModel.oData,
				orderDetail: obj
			});

			var that = this;
			// var oModel = new sap.ui.model.odata.v2.ODataModel("/sap/opu/odata/sap/ZGBLMTORDER_TRN_SRV/", {
			// 	serviceUrl: "/sap",
			// 	useBatch: false
			// });
			var oModel = this.getView().getModel();
			oModel.read("/ENTITY001Set('" + id + "')", {
				success: function (oData, oResponse) {
					that.filterData(oData);
				},
				error: function (oError) {
					// 获取数据失败的处理逻辑
				}
			});
		},

		getInfoItem(url) {
			return new Promise((resolve, reject) => {
				var oModel = this.getView().getModel();
				oModel.read(url, {
					success: function (oData, oResponse) {
						resolve(oData);
					},
					error: function (oError) {
						reject(oError);
					}
				});
			});
		},

		repairOrder() {
			var oModel = this.getView().getModel();
			var oEntry = {};
			var that = this;
			oEntry.statusNo = "REPAIR";
			oEntry.action = "REPAIR";
			oModel.update("/ENTITY001Set('" + this.orderInfo.orderNo + "')", oEntry, {
				success: function (data) {
					// location.reload();
					that.refreshTable();
				},
				error: function (error) {
					// 创建失败后的处理逻辑
					sap.m.MessageToast.show(error.message);
				}
			});
		},

		deleteOrder() {
			var oModel = this.getView().getModel();
			var that = this;
			var oEntry = {};
			oEntry.statusNo = "DELETE";
			oEntry.action = "DELETE";
			oModel.update("/ENTITY001Set('" + this.orderInfo.orderNo + "')", oEntry, {
				success: function (data) {
					// location.reload();
					that.refreshTable();
				},
				error: function (error) {
					// 创建失败后的处理逻辑
					sap.m.MessageToast.show(error.message);
				}
			});

			// //删除方法的后端接口没有挂载
			// oModel.remove("/ENTITY001Set('" + this.orderInfo.orderNo + "')", {
			// 	success: function (data) {
			// 		window.location.href = "http://localhost:8080/index.html";
			// 	},
			// 	error: function (error) {
			// 		// 创建失败后的处理逻辑
			// 	}
			// });
		},

		closeOrder() {
			var oModel = this.getView().getModel();
			var that = this;
			var oEntry = {};
			oEntry.statusNo = "CLOSED";
			oEntry.action = "CLOSE";
			oModel.update("/ENTITY001Set('" + this.orderInfo.orderNo + "')", oEntry, {
				success: function (data) {
					// location.reload();
					that.refreshTable();
				},
				error: function (error) {
					// 创建失败后的处理逻辑
					sap.m.MessageToast.show(error.message);
				}
			});

		}
	});
});